
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.dto.terminal.DictTerminalConfigDto;
import com.rt.schedulebase.entity.*;
import com.rt.schedulebase.mapper.DictSysparamsMapper;
import com.rt.schedulebase.mapper.DictTerminalConfigMapper;
import com.rt.schedulebase.mapper.DictTerminalMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DictTerminalServiceImpl extends ServiceImpl<DictTerminalMapper, DictTerminal> implements IDictTerminalService {
    @Autowired
    private DictTerminalMapper dictTerminalMapper;

    @Autowired
    private DictTerminalConfigMapper dictTerminalConfigMapper;
    @Autowired
    private DictSysparamsMapper dictSysparamsMapper;
    @Autowired
    private IDictHospitalService dictHospitalService;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private IDictDeptService dictDeptService;
    @Autowired
    private IDictSerialService dictSerialService;

    @Override
    public DictTerminalDto getSelfDeviceInfo(DictTerminalDto dto) {
        DictTerminalDto newTerminalDto = null;
        DictTerminal dictTerminal = selectTerminalById(dto);

        if (ObjectUtils.isNotEmpty(dictTerminal)) {
            QueryWrapper<DictTerminalConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("TERMINAL_ID", dictTerminal.getId());
            DictTerminalConfig config = dictTerminalConfigMapper.selectOne(queryWrapper);

            newTerminalDto = new DictTerminalDto();
            BeanUtils.copyProperties(dictTerminal, newTerminalDto);
            if (ObjectUtils.isNotEmpty(config)) {
                newTerminalDto.setIsReadCard(config.getIsReadCard());
                newTerminalDto.setScheduleExamClass(config.getScheduleExamClass());
                newTerminalDto.setSignExamClass(config.getSignExamClass());
                newTerminalDto.setDirectClass(config.getDirectClass());
                newTerminalDto.setUnSchedulePatientSource(config.getUnSchedulePatientSource());
                newTerminalDto.setUnSignQueue(config.getUnSignQueue());
                newTerminalDto.setIsSchedulePlan(config.getIsSchedulePlan());
                newTerminalDto.setIsReadCard(config.getIsReadCard());
                newTerminalDto.setIsSignNow(config.getIsSignNow());

                newTerminalDto.setPrinterName(config.getPrinterName());
                newTerminalDto.setScheduleQueue(config.getScheduleQueue());
                newTerminalDto.setSignQueue(config.getSignQueue());
                newTerminalDto.setIcCardInputSupportType(config.getIcCardInputSupportType());
                newTerminalDto.setFunctionButtons(config.getFunctionButtons());
                if (StringUtils.isNotBlank(newTerminalDto.getFunctionButtons())) {
                    newTerminalDto.setFunctionButton(JsonUtil.toList(newTerminalDto.getFunctionButtons(), DictTerminalDto.FunctionButton.class));
                }
            }
        }

//        if (ObjectUtils.isNotEmpty(dictTerminal)) {
//            newTerminalDto = new DictTerminalDto();
//            BeanUtils.copyProperties(dictTerminal, newTerminalDto);
//            // 构建配置文件
//            newTerminalDto.buildConfigDto();
//        }
        return newTerminalDto;
    }


    private DictTerminalDto getSelfConfig(DictTerminal terminal) {
        DictTerminalDto newTerminalDto = new DictTerminalDto();
        String deviceId = StringUtils.isNotBlank(terminal.getIpAddress()) ? terminal.getIpAddress() : terminal.getTerminalCode();
        BeanUtils.copyProperties(terminal, newTerminalDto);
        newTerminalDto.setDeviceId(deviceId);
        QueryWrapper<DictSysparams> sysparamsQueryWrapper = new QueryWrapper<>();
        sysparamsQueryWrapper.eq("DEVICE_CODE", deviceId);
        List<DictSysparams> sysparamsList = dictSysparamsMapper.selectList(sysparamsQueryWrapper);
        if (sysparamsList != null && !sysparamsList.isEmpty()) {
            for (DictSysparams sysparams : sysparamsList) {
                if (ConstantsUtil.SelfConfigName.SELF_SCHEDULE_EXAM_CLASS.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setScheduleExamClass(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_SIGN_EXAM_CLASS.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setSignExamClass(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_DIRECT_CLASS.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setDirectClass(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_UN_SCHEDULE_PATIENT_SOURCE.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setUnSchedulePatientSource(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_UN_SIGN_QUEUE.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setUnSignQueue(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_IS_SCHEDULE_PLAN.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setIsSchedulePlan(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "0");
                }
                if (ConstantsUtil.SelfConfigName.SELF_IS_READ_CARD.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setIsReadCard(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "0");
                }
                if (ConstantsUtil.SelfConfigName.SELF_IS_SIGN_NOW.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setIsSignNow(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "0");
                }
                if (ConstantsUtil.SelfConfigName.SELF_PRINTER_NAME.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setPrinterName(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "");
                }
                if (ConstantsUtil.SelfConfigName.SELF_FUNCTION_BUTTON.getKey().equals(sysparams.getParamName()) && StringUtils.isNotBlank(sysparams.getParamValue())) {
                    List<String> functionButtonList = CommonUtil.split2List(sysparams.getParamValue());
                    if (!functionButtonList.isEmpty()) {
                        List<com.rt.schedulebase.dto.DictTerminalDto.FunctionButton> buttonList = new ArrayList<>();
                        for (int i = 0; i < functionButtonList.size(); ++i) {
                            String functionButton = functionButtonList.get(i);
                            com.rt.schedulebase.dto.DictTerminalDto.FunctionButton button = new com.rt.schedulebase.dto.DictTerminalDto.FunctionButton();
                            String[] arr = functionButton.split("_");
                            String code = StringUtils.isNotBlank(arr[0]) ? arr[0] : ("F0" + (i + 1));
                            button.setCode(code);
                            button.setName(arr[1]);
                            button.setEnable(arr[2]);
                            String itemName = null;
                            if (ConstantsUtil.SelfFunction.TAKE_NO.key.equals(code)) {
                                itemName = ConstantsUtil.SelfFunction.TAKE_NO.value;
                            } else if (ConstantsUtil.SelfFunction.SCHEDULE.key.equals(code)) {
                                itemName = ConstantsUtil.SelfFunction.SCHEDULE.value;
                            } else if (ConstantsUtil.SelfFunction.SIGN.key.equals(code)) {
                                itemName = ConstantsUtil.SelfFunction.SIGN.value;
                            } else if (ConstantsUtil.SelfFunction.WAIT.key.equals(code)) {
                                itemName = ConstantsUtil.SelfFunction.WAIT.value;
                            } else if (ConstantsUtil.SelfFunction.REPORT.key.equals(code)) {
                                itemName = ConstantsUtil.SelfFunction.REPORT.value;
                            }
                            button.setItemName(itemName);
                            buttonList.add(button);
                        }
                        newTerminalDto.setFunctionButton(buttonList);
                    }
                }
                if (ConstantsUtil.SelfConfigName.SELF_IC_CARD_INPUT_SUPPORT_TYPE.getKey().equals(sysparams.getParamName())) {
                    newTerminalDto.setIcCardInputSupportType(StringUtils.isNotBlank(sysparams.getParamValue()) ? sysparams.getParamValue() : "common_card");
                }
            }
        }
        DictHospitalDto dictHospitalDto = new DictHospitalDto();
        dictHospitalDto.setHospitalCode(terminal.getHospitalCode());
        List<DictHospital> hospitalList = dictHospitalService.selectList(dictHospitalDto);
        if (hospitalList != null && !hospitalList.isEmpty()) {
            newTerminalDto.setHospitalName(hospitalList.get(0).getHospitalName());
        }
        DictDeptDto dictDeptDto = new DictDeptDto();
        dictDeptDto.setDeptCode(terminal.getDeptCode());
        List<DictDept> deptList = dictDeptService.getList(dictDeptDto);
        if (deptList != null && !deptList.isEmpty()) {
            newTerminalDto.setDeptName(deptList.get(0).getDeptName());
        }
        return newTerminalDto;
    }

    /**
     * 获取自助机配置列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<DictTerminalDto> selectList(DictTerminalDto dto) {
//        QueryWrapper<DictTerminal> terminalQueryWrapper = new QueryWrapper<>();
//        if (StringUtils.isNotBlank(dto.getHospitalCode())) {
//            terminalQueryWrapper.eq("HOSPITAL_CODE", dto.getHospitalCode());
//        }
//        if (StringUtils.isNotBlank(dto.getDeptCode())) {
//            terminalQueryWrapper.eq("DEPT_CODE", dto.getDeptCode());
//        }
////        if (StringUtils.isNotBlank(dto.getScheduleExamClass())) {
////            DictSysparamsDto dictSysparamsDto = new DictSysparamsDto();
////            dictSysparamsDto.setParamName(ConstantsUtil.SelfConfigName.SELF_SCHEDULE_EXAM_CLASS.getKey());
////            dictSysparamsDto.setParamValues(CommonUtil.split2List(dto.getScheduleExamClass()));
////            List<String> deviceCodeList = dictSysparamsMapper.getDeviceCodesByName(dictSysparamsDto);
////            if (deviceCodeList != null && !deviceCodeList.isEmpty()) {
////                terminalQueryWrapper.in("IP_ADDRESS", deviceCodeList);
////            }
////        }
////        if (StringUtils.isNotBlank(dto.getSignExamClass())) {
////            DictSysparamsDto dictSysparamsDto = new DictSysparamsDto();
////            dictSysparamsDto.setParamName(ConstantsUtil.SelfConfigName.SELF_SIGN_EXAM_CLASS.getKey());
////            dictSysparamsDto.setParamValues(CommonUtil.split2List(dto.getSignExamClass()));
////            List<String> deviceCodeList = dictSysparamsMapper.getDeviceCodesByName(dictSysparamsDto);
////            if (deviceCodeList != null && !deviceCodeList.isEmpty()) {
////                terminalQueryWrapper.in("IP_ADDRESS", deviceCodeList);
////            }
////        }
//        if (StringUtils.isNotBlank(dto.getDeviceId())) {
//            ((terminalQueryWrapper.eq("TERMINAL_NAME", dto.getDeviceId())).or())
//                    .eq("IP_ADDRESS", dto.getDeviceId());
//        }
//        terminalQueryWrapper.eq("TERMINAL_TYPE", ConstantsUtil.TerminalType.SELF.getType());
//        terminalQueryWrapper.orderByAsc("TERMINAL_CODE");
//        List<DictTerminal> terminalDtoList = dictTerminalMapper.selectList(terminalQueryWrapper);
//
//        // 将terminal 改成 terminalDto
//        List<DictTerminalDto> list = new ArrayList<>();
//        if (CollectionUtils.isNotEmpty(terminalDtoList)) {
//            for (DictTerminal terminal : terminalDtoList) {
//                DictTerminalDto terminalDto = new DictTerminalDto();
//                BeanUtils.copyProperties(terminal, terminalDto);
//                // 构建配置文件
//                terminalDto.buildConfigDto();
//                list.add(terminalDto);
//            }
//        }
        List<DictTerminalDto> dtos = dictTerminalMapper.selectList(dto);
        if (CollectionUtils.isNotEmpty(dtos)) {
            dtos.forEach(x -> {
                if (StringUtils.isNotBlank(x.getFunctionButtons())) {
                    x.setFunctionButton(JsonUtil.toList(x.getFunctionButtons(), com.rt.schedulebase.dto.DictTerminalDto.FunctionButton.class));
                }
            });
        }
        return dtos;
    }

    @Override
    public List<DictTerminalDto> selectWitConfigList(DictTerminalDto p0) {
        return null;
    }

    @Override
    public DictTerminal selectTerminalById(DictTerminalDto dto) {
        QueryWrapper<DictTerminal> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getTerminalCode())) {
            queryWrapper.eq("TERMINAL_CODE", dto.getTerminalCode());
        }
        if (StringUtils.isNotBlank(dto.getIpAddress())) {
            queryWrapper.eq("IP_ADDRESS", dto.getIpAddress());
        }
        queryWrapper.eq("TERMINAL_TYPE", ConstantsUtil.TerminalType.SELF.getType());
        return dictTerminalMapper.selectOne(queryWrapper);
    }

    /***
     * 修改时按照ip和terminalCode判断
     * 新增时只按照ip判断是否存在
     * @param dto terminalCode 、 ipaddress
     * @return false 不重复 true 重复,参数错误 也返回true
     */
    @Override
    public boolean checkTerminalIPIsRepeat(DictTerminalDto dto, boolean isCreate) {
        if (StringUtils.isEmpty(dto.getIpAddress())) {
            return true;
        }
        if (!isCreate) {
            if (StringUtils.isBlank(dto.getTerminalCode())) {
                return true;
            }
        }

        QueryWrapper<DictTerminal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IP_ADDRESS", dto.getIpAddress());
        if (!isCreate) {
            queryWrapper.ne("TERMINAL_CODE", dto.getTerminalCode());
        }
        queryWrapper.eq("TERMINAL_TYPE", ConstantsUtil.TerminalType.SELF.getType());

        return dictTerminalMapper.selectCount(queryWrapper) > 0;
    }

    private String getTerminalCode(int n) {
        String terminalCode = dictSerialService.getSerialId("SELF_TERMINAL_CODE");
        QueryWrapper<DictTerminal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TERMINAL_CODE", terminalCode);
        if (n < 30 && dictTerminalMapper.selectCount(queryWrapper) > 0) {
            ++n;
            return getTerminalCode(n);
        }
        return terminalCode;
    }

    @Override
    @Transactional
    public JsonResult saveSelfDevice(DictTerminalDto dto) {
        DictUsersDto dictUsers = commonService.dictUsers(new ExamApplyDto());
        if (dictUsers == null) {
            return null;
        }
        DictTerminal dictTerminal = selectTerminalById(dto);
        if (dictTerminal != null) {
            return JsonResultUtil.failure("已存在这条[" + dto.getIpAddress() + "]自助机设备信息");
        }
        String terminalCode = getTerminalCode(0);
        DictTerminalDto terminal = new DictTerminalDto();
        BeanUtils.copyProperties(dto, terminal);
        terminal.setTerminalCode(terminalCode);
        terminal.setIpAddress(StringUtils.isNotBlank(dto.getIpAddress()) ? dto.getIpAddress() : terminalCode);
        terminal.setUserName(dictUsers.getName());
        terminal.setUserId(dictUsers.getUserId());
        terminal.setTerminalType(ConstantsUtil.TerminalType.SELF.getType());
        int result = dictTerminalMapper.insert(terminal);
        if (result > 0) {
            saveTerminalConfig(terminal);
            return JsonResultUtil.success("新增成功");
        }
        return JsonResultUtil.failure("新增失败");
    }

    /***
     * 构建终端配置信息
     * @param terminal
     */
    private void buildTerminalConfig(DictTerminalDto terminal) {
        DictTerminalConfigDto configDto = new DictTerminalConfigDto();
        configDto.setScheduleExamClass(terminal.getScheduleExamClass());

        configDto.setDirectClass(terminal.getDirectClass());
        configDto.setUnSchedulePatientSource(terminal.getUnSchedulePatientSource());
        configDto.setUnSignQueue(terminal.getUnSignQueue());
        configDto.setIsSchedulePlan(terminal.getIsSchedulePlan());
        configDto.setIsReadCard(terminal.getIsReadCard());
        configDto.setIsSignNow(terminal.getIsSignNow());
        configDto.setPrinterName(terminal.getPrinterName());
        configDto.setFunctionButton(terminal.getFunctionButtons());
        configDto.setIcCardInputSupportType(terminal.getIcCardInputSupportType());
        configDto.setFunctionButton(terminal.getFunctionButtons());
        configDto.setSignExamClass(terminal.getSignExamClass());

        terminal.setConfig(JsonUtil.toJson(configDto));
    }

    public void saveTerminalConfig(DictTerminalDto terminal) {
        boolean isNew = false;
        DictTerminalConfig terminalConfig = dictTerminalConfigMapper
                .selectByTerminalId(terminal.getId());

        if (ObjectUtils.isEmpty(terminalConfig)) {
            isNew = true;
            terminalConfig = new DictTerminalConfig();
        }
        terminalConfig.setTerminalId(terminal.getId());
        terminalConfig.setScheduleExamClass(terminal.getScheduleExamClass());
        terminalConfig.setDirectClass(terminal.getDirectClass());
        terminalConfig.setUnSchedulePatientSource(terminal.getUnSchedulePatientSource());
        terminalConfig.setUnSignQueue(terminal.getUnSignQueue());
        terminalConfig.setIsSchedulePlan(terminal.getIsSchedulePlan());
        terminalConfig.setIsReadCard(terminal.getIsReadCard());
        terminalConfig.setIsSignNow(terminal.getIsSignNow());
        terminalConfig.setPrinterName(terminal.getPrinterName());
        terminalConfig.setIcCardInputSupportType(terminal.getIcCardInputSupportType());
        terminalConfig.setSignExamClass(terminal.getSignExamClass());

        String functionButtons = terminal.getFunctionButtons();
        List<com.rt.schedulebase.dto.DictTerminalDto.FunctionButton> buttonList = new ArrayList<>();
        if (StringUtils.isNotBlank(functionButtons)) {
            List<String> functionButtonList = CommonUtil.split2List(functionButtons);
            if (CollectionUtils.isNotEmpty(functionButtonList)) {
                for (int i = 0; i < functionButtonList.size(); ++i) {
                    String functionButton = functionButtonList.get(i);
                    com.rt.schedulebase.dto.DictTerminalDto.FunctionButton button = new com.rt.schedulebase.dto.DictTerminalDto.FunctionButton();
                    String[] arr = functionButton.split("_");
                    String code = StringUtils.isNotBlank(arr[0]) ? arr[0] : ("F0" + (i + 1));
                    button.setCode(code);
                    button.setName(arr[1]);
                    button.setEnable(arr[2]);
                    String itemName = null;
                    if (ConstantsUtil.SelfFunction.TAKE_NO.key.equals(code)) {
                        itemName = ConstantsUtil.SelfFunction.TAKE_NO.value;
                    } else if (ConstantsUtil.SelfFunction.SCHEDULE.key.equals(code)) {
                        itemName = ConstantsUtil.SelfFunction.SCHEDULE.value;
                    } else if (ConstantsUtil.SelfFunction.SIGN.key.equals(code)) {
                        itemName = ConstantsUtil.SelfFunction.SIGN.value;
                    } else if (ConstantsUtil.SelfFunction.WAIT.key.equals(code)) {
                        itemName = ConstantsUtil.SelfFunction.WAIT.value;
                    } else if (ConstantsUtil.SelfFunction.REPORT.key.equals(code)) {
                        itemName = ConstantsUtil.SelfFunction.REPORT.value;
                    }
                    button.setItemName(itemName);
                    buttonList.add(button);
                }
            }
        }
        terminalConfig.setFunctionButtons(JsonUtil.toJson(buttonList));

        if (isNew) {
            dictTerminalConfigMapper.insert(terminalConfig);
        } else {
            UpdateWrapper<DictTerminalConfig> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", terminalConfig.getId());
            dictTerminalConfigMapper.update(terminalConfig, updateWrapper);
        }
    }

    /***
     * 保存自助机环境变量
     * @param terminal 自助机配置信息
     */
    private void saveSysparmsInfo4Self(DictTerminalDto terminal) {
        try {
            List<DictSysparams> sysparamsList = new ArrayList<>();
            if (terminal.getScheduleExamClass() != null) {
                DictSysparams scheduleExamClass = new DictSysparams();
                scheduleExamClass.setParamName(ConstantsUtil.SelfConfigName.SELF_SCHEDULE_EXAM_CLASS.getKey());
                scheduleExamClass.setParamValue(terminal.getScheduleExamClass());
                scheduleExamClass.setMemo("【自助机---预约检查类别】(多个用英文逗号“,”分隔)");
                scheduleExamClass.setDeviceCode(terminal.getIpAddress());
                scheduleExamClass.setUserId(terminal.getUserId());
                sysparamsList.add(scheduleExamClass);
            }
            if (terminal.getSignExamClass() != null) {
                DictSysparams signExamClass = new DictSysparams();
                signExamClass.setParamName(ConstantsUtil.SelfConfigName.SELF_SIGN_EXAM_CLASS.getKey());
                signExamClass.setParamValue(terminal.getSignExamClass());
                signExamClass.setMemo("【自助机---报到检查类别】(多个用英文逗号“,”分隔)");
                signExamClass.setDeviceCode(terminal.getIpAddress());
                signExamClass.setUserId(terminal.getUserId());
                sysparamsList.add(signExamClass);
            }
            if (terminal.getDirectClass() != null) {
                DictSysparams directClass = new DictSysparams();
                directClass.setParamName(ConstantsUtil.SelfConfigName.SELF_DIRECT_CLASS.getKey());
                directClass.setParamValue(terminal.getDirectClass());
                directClass.setMemo("【自助机---无需预约直接报到检查类别】");
                directClass.setDeviceCode(terminal.getIpAddress());
                directClass.setUserId(terminal.getUserId());
                sysparamsList.add(directClass);
            }
            if (terminal.getUnSchedulePatientSource() != null) {
                DictSysparams unSchedulePatientSource = new DictSysparams();
                unSchedulePatientSource.setParamName(ConstantsUtil.SelfConfigName.SELF_UN_SCHEDULE_PATIENT_SOURCE.getKey());
                unSchedulePatientSource.setParamValue(terminal.getUnSchedulePatientSource());
                unSchedulePatientSource.setMemo("【自助机---不能在自助机预约的病人来源】(多个用英文逗号“,”分隔)");
                unSchedulePatientSource.setDeviceCode(terminal.getIpAddress());
                unSchedulePatientSource.setUserId(terminal.getUserId());
                sysparamsList.add(unSchedulePatientSource);
            }
            if (terminal.getUnSignQueue() != null) {
                DictSysparams unSignQueue = new DictSysparams();
                unSignQueue.setParamName(ConstantsUtil.SelfConfigName.SELF_UN_SIGN_QUEUE.getKey());
                unSignQueue.setParamValue(terminal.getUnSignQueue());
                unSignQueue.setMemo("【自助机---不能在自助机报到的队列】(多个用英文逗号“,”分隔)");
                unSignQueue.setDeviceCode(terminal.getIpAddress());
                unSignQueue.setUserId(terminal.getUserId());
                sysparamsList.add(unSignQueue);
            }
            if (terminal.getIsSchedulePlan() != null) {
                DictSysparams isSchedulePlan = new DictSysparams();
                isSchedulePlan.setParamName(ConstantsUtil.SelfConfigName.SELF_IS_SCHEDULE_PLAN.getKey());
                isSchedulePlan.setParamValue(StringUtils.isNotBlank(terminal.getIsSchedulePlan()) ? terminal.getIsSchedulePlan() : "0");
                isSchedulePlan.setMemo("【自助机---是否开启预约计划】（1：是    0：否）");
                isSchedulePlan.setDeviceCode(terminal.getIpAddress());
                isSchedulePlan.setUserId(terminal.getUserId());
                sysparamsList.add(isSchedulePlan);
            }
            if (terminal.getIsReadCard() != null) {
                DictSysparams isReadCard = new DictSysparams();
                isReadCard.setParamName(ConstantsUtil.SelfConfigName.SELF_IS_READ_CARD.getKey());
                isReadCard.setParamValue(StringUtils.isNotBlank(terminal.getIsReadCard()) ? terminal.getIsReadCard() : "0");
                isReadCard.setMemo("【自助机---是否开启读卡】（1：是    0：否）");
                isReadCard.setDeviceCode(terminal.getIpAddress());
                isReadCard.setUserId(terminal.getUserId());
                sysparamsList.add(isReadCard);
            }
            if (terminal.getIsSignNow() != null) {
                DictSysparams isSignNow = new DictSysparams();
                isSignNow.setParamName(ConstantsUtil.SelfConfigName.SELF_IS_SIGN_NOW.getKey());
                isSignNow.setParamValue(StringUtils.isNotBlank(terminal.getIsSignNow()) ? terminal.getIsSignNow() : "0");
                isSignNow.setMemo("【自助机---是否开启立即报到】（1：是    0：否）");
                isSignNow.setDeviceCode(terminal.getIpAddress());
                isSignNow.setUserId(terminal.getUserId());
                sysparamsList.add(isSignNow);
            }
            if (terminal.getPrinterName() != null) {
                DictSysparams printerName = new DictSysparams();
                printerName.setParamName(ConstantsUtil.SelfConfigName.SELF_PRINTER_NAME.getKey());
                printerName.setParamValue(terminal.getPrinterName());
                printerName.setMemo("【自助机---打印机名称】");
                printerName.setDeviceCode(terminal.getIpAddress());
                printerName.setUserId(terminal.getUserId());
                sysparamsList.add(printerName);
            }
            if (terminal.getFunctionButtons() != null) {
                DictSysparams functionButtons = new DictSysparams();
                functionButtons.setParamName(ConstantsUtil.SelfConfigName.SELF_FUNCTION_BUTTON.getKey());
                functionButtons.setParamValue(terminal.getFunctionButtons());
                functionButtons.setMemo("【自助机---引导页功能模块】");
                functionButtons.setDeviceCode(terminal.getIpAddress());
                functionButtons.setUserId(terminal.getUserId());
                sysparamsList.add(functionButtons);
            }
            if (terminal.getIcCardInputSupportType() != null) {
                DictSysparams icCardInputSupportType = new DictSysparams();
                icCardInputSupportType.setParamName(ConstantsUtil.SelfConfigName.SELF_IC_CARD_INPUT_SUPPORT_TYPE.getKey());
                icCardInputSupportType.setParamValue(terminal.getIcCardInputSupportType());
                icCardInputSupportType.setMemo("【自助机---输入卡号框对应的卡号类型】(注:该配置值只能填单值)综合号码（common_card）、病人标识号（sick_id）、诊疗卡号（ic_card）、住院号（inpatient_no）、门诊号（outpatient_no）、申请单号（apply_no）、身份证号（identity_card）、医保卡号（mi_card）、健康卡号（health_card）");
                icCardInputSupportType.setDeviceCode(terminal.getIpAddress());
                icCardInputSupportType.setUserId(terminal.getUserId());
                sysparamsList.add(icCardInputSupportType);
            }
            for (DictSysparams sysparams : sysparamsList) {
                QueryWrapper<DictSysparams> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PARAM_NAME", sysparams.getParamName());
                queryWrapper.eq("DEVICE_CODE", sysparams.getDeviceCode());
                Integer resultCount = dictSysparamsMapper.selectCount(queryWrapper);
                if (resultCount != null && resultCount > 0) {
                    dictSysparamsMapper.updateSysparmsInfo(sysparams);
                } else {
                    dictSysparamsMapper.insertSysparmsInfo(sysparams);
                }
            }
        } catch (Exception e) {
            log.error("saveSysparmsInfo4Self" + e.getMessage(), e);
        }
    }

    @Override
    public JsonResult editSelfDevice(DictTerminalDto dto) {
        /**
         * 参数验证
         */
        if (StringUtils.isEmpty(dto.getTerminalCode())) {
            return JsonResultUtil.failure("请求参数错误[terminalCode不存在]");
        }
        if (StringUtils.isEmpty(dto.getIpAddress())) {
            return JsonResultUtil.failure("请求参数错误[ipAddress不存在]");
        }

        /***
         * 验证编码
         */
        DictTerminalDto terminalDto = new DictTerminalDto();
        terminalDto.setTerminalCode(dto.getTerminalCode());
        DictTerminal dictTerminal = selectTerminalById(terminalDto);
        if (ObjectUtils.isEmpty(dictTerminal)) {
            return JsonResultUtil.failure("不存在这条[" + dto.getTerminalCode() + "]自助机设备信息");
        }

        /**
         * 验证ip是否已存在
         */
        //boolean isRepeat = checkTerminalIPIsRepeat(dto, false);
        QueryWrapper<DictTerminal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IP_ADDRESS", dto.getIpAddress());
        // queryWrapper.ne("TERMINAL_CODE", dto.getTerminalCode());
        queryWrapper.eq("TERMINAL_TYPE", ConstantsUtil.TerminalType.SELF.getType());

        DictTerminal terminal = dictTerminalMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(terminal) && !terminal.getTerminalCode().equals(dto.getTerminalCode())) {
            return JsonResultUtil.failure("已存在这条[" + dto.getIpAddress() + "]自助机设备信息");
        }
        dto.setId(terminal.getId());
        BeanUtils.copyProperties(dto, terminalDto);

        DictUsersDto dictUsers = commonService.getLoginUser();
        if (ObjectUtils.isNotEmpty(dictUsers)) {
            terminalDto.setUserName(dictUsers.getName());
            terminalDto.setUserId(dictUsers.getUserId());
        }

        terminalDto.setTerminalType(ConstantsUtil.TerminalType.SELF.getType());

        UpdateWrapper<DictTerminal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("TERMINAL_CODE", dto.getTerminalCode());
        int result = dictTerminalMapper.update(terminalDto, updateWrapper);
        if (result > 0) {
            saveTerminalConfig(terminalDto);
            return JsonResultUtil.success("修改成功");
        }
        return JsonResultUtil.failure("修改失败");
    }

    @Override
    public JsonResult deleteSelfDevice(DictTerminalDto dto) {
        DictTerminal dictTerminal = selectTerminalById(dto);
        if (dictTerminal == null) {
            return JsonResultUtil.failure("不存在这条[" + dto.getTerminalCode() + "]自助机设备信息");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("TERMINAL_CODE", dto.getTerminalCode());
        int result = dictTerminalMapper.deleteByMap(map);
        if (result > 0) {
            map = new HashMap<>();
            map.put("DEVICE_CODE", dictTerminal.getIpAddress());
            dictSysparamsMapper.deleteByMap(map);
            return JsonResultUtil.success("删除成功");
        }
        return JsonResultUtil.failure("删除失败");
    }
}
